package com.le.tester.javaThink.fifth.chapter12_Collections;

import java.util.*;

/**
 * createTime：2021/8/31 17:55
 * description：AdapterMethodIdiom
 */

class ReversibleArrayList<T> extends ArrayList<T> {
    ReversibleArrayList(Collection<T> c) {
        super(c);
    }

    public Iterable<T> reversed() {
        return new Iterable<T>() {
            @Override
            public Iterator<T> iterator() {
                return new Iterator<T>() {
                    int curSize = size() - 1;

                    @Override
                    public boolean hasNext() {
                        return curSize > -1;
                    }

                    @Override
                    public T next() {
                        return get(curSize--);
                    }

                    @Override
                    public void remove() {
                        throw new UnsupportedOperationException();
                    }
                };
            }
        };
    }
}

public class AdapterMethodIdiom {
    public static void main(String[] args) {
        ReversibleArrayList<String> ral = new ReversibleArrayList<>(Arrays.asList("To be or not to be".split(" ")));

        for (String s : ral)
            System.out.print(s + " ");
        System.out.println();

        for (String s : ral.reversed())
            System.out.print(s + " ");
    }
}
